package com.espirit.eap.manager.workflow;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.espirit.eap.sa.LoginUser;
import com.espirit.eap.util.StatGenericJPAService;
import com.googlecode.cswish.annotation.GenericType;

@Service
public class WFPhaseService {
	@Resource
	StatGenericJPAService genericService;
	
	public void add(@GenericType Object model){
		WFPhase phase = (WFPhase)model;
		phase.initUsers();
		setNeedAcceptUsers(phase);
		phase.verify();
		genericService.add(phase);
	}
	
	
	private void setNeedAcceptUsers(WFPhase phase){
		if (phase.getUsers() != null && !phase.getUsers().isEmpty()){
			int size = phase.getUsers().size();
			if (phase.getNeedAcceptUsers() == null || phase.getNeedAcceptUsers().equals(0)){
				phase.setNeedAcceptUsers(size);
			} else {
				if (phase.getNeedAcceptUsers() > size){
					phase.setNeedAcceptUsers(size);
				}
			}
		} else {
			phase.setNeedAcceptUsers(null);
		}
	}
	
	public Object _update(@GenericType Object model) {
    	WFPhase phase = (WFPhase)model;
    	phase = genericService.load(phase);
    	
    	WFCondition condition = phase.safeWFCondtion();
    	if (condition.getAcceptTrigger() == null){
    		condition.setAcceptTrigger(WFCondition.ACCEPT_TRIGGER_ALWAYS);
    	}
    	
    	if (phase.getUsers() != null ) {
			List<LoginUser> users = phase.getUsers();
			for(int i = 0; i < users.size() ; i++){
				LoginUser user = users.get(i);
				user.setUsers(user);
			}
		}
    	setNeedAcceptUsers(phase);
		return genericService.view(model);
    }
	
	public void update(@GenericType Object model){
		WFPhase phase = (WFPhase)model;
		phase.initUsers();
		phase.verify();
		genericService.update(model);
	}
	
	public LoginUser getNextUser(){
		return null;
	}
}
